<?php
/**
 * 返回经addslashes处理过的字符串或数组
 * @param $string 需要处理的字符串或数组
 * @return mixed
 */
function new_addslashes($string)
{
    if (!is_array($string)) return addslashes($string);
    foreach ($string as $key => $val) $string[$key] = new_addslashes($val);
    return $string;
}

/**
 * 返回经stripslashes处理过的字符串或数组
 * @param $string 需要处理的字符串或数组
 * @return mixed
 */
function new_stripslashes($string)
{
    if (!is_array($string)) return stripslashes($string);
    foreach ($string as $key => $val) $string[$key] = new_stripslashes($val);
    return $string;
}

/**
 * 返回经htmlspecialchars处理过的字符串或数组
 * @param $obj 需要处理的字符串或数组
 * @return mixed
 */
function new_html_special_chars($string)
{
    $encoding = 'utf-8';
    if (strtolower(CHARSET) == 'gbk') $encoding = 'ISO-8859-15';
    if (!is_array($string)) return htmlspecialchars($string, ENT_QUOTES, $encoding);
    foreach ($string as $key => $val) $string[$key] = new_html_special_chars($val);
    return $string;
}

function new_html_entity_decode($string)
{
    $encoding = 'utf-8';
    if (strtolower(CHARSET) == 'gbk') $encoding = 'ISO-8859-15';
    return html_entity_decode($string, ENT_QUOTES, $encoding);
}

function new_htmlentities($string)
{
    $encoding = 'utf-8';
    if (strtolower(CHARSET) == 'gbk') $encoding = 'ISO-8859-15';
    return htmlentities($string, ENT_QUOTES, $encoding);
}

/**
 * 安全过滤函数
 *
 * @param $string
 * @return string
 */
function safe_replace($string)
{
    $string = str_replace('%20', '', $string);
    $string = str_replace('%27', '', $string);
    $string = str_replace('%2527', '', $string);
    $string = str_replace('*', '', $string);
    $string = str_replace('"', '"', $string);
    $string = str_replace("'", '', $string);
    $string = str_replace('"', '', $string);
    $string = str_replace(';', '', $string);
    $string = str_replace('<', '<', $string);
    $string = str_replace('>', '>', $string);
    $string = str_replace("{", '', $string);
    $string = str_replace('}', '', $string);
    $string = str_replace('\\', '', $string);
    return $string;
}

/**
 * xss过滤函数
 *
 * @param $string
 * @return string
 */
function remove_xss($string)
{
    $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string);
    $parm1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
    $parm2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
    $parm = array_merge($parm1, $parm2);
    for ($i = 0; $i < sizeof($parm); $i++) {
        $pattern = '/';
        for ($j = 0; $j < strlen($parm[$i]); $j++) {
            if ($j > 0) {
                $pattern .= '(';
                $pattern .= '(&#[x|X]0([9][a][b]);?)?';
                $pattern .= '|(�([9][10][13]);?)?';
                $pattern .= ')?';
            }
            $pattern .= $parm[$i][$j];
        }
        $pattern .= '/i';
        $string = preg_replace($pattern, ' ', $string);
    }
    return $string;
}

//短信发送方法
function sendSms($mobile, $content)
{
    $account = C('smsname');
    $password = C('smspwd');
    $prouctID = C('smsproductid');
    $account = C('smsgjname');
    $password = C('smsgjpwd');
    $prouctID = C('smsgjproductid');
    $statusStr = array(
        "0" => "发送短信失败",
        "-1" => "用户名或者密码不正确或用户禁用或者是管理账户",
        "1" =>  "短信发送成功",
        "2" => "余额不够或扣费错误",
        "3" => "扣费失败异常（请联系客服）",
        "6" => "有效号码为空",
        "7" => "短信内容为空",
        "8" => "无签名，必须，格式：【签名】",
        "9" => "没有Url提交权限",
        "10" => "发送号码过多,最多支持2000个号码",
        "11" => "产品ID异常或产品禁用",
        "12" => "参数异常",
        "13" => "tkey参数错误",
        "15" => "Ip验证失败",
        "16" => "xh参数错误",
        "19" => "短信内容过长，最多支持500个,或提交编码异常导致",
    );
    $smsapi = "http://www.ztsms.cn/sendNSms.do"; //短信网关
    $user = $account; //短信平台帐号
    $tkey = date("YmdHis",time());
    $pass = md5(md5($password).$tkey); //短信平台密码
    $content = $content;//要发送的短信内容
    $phone = $mobile;
    $sendurl = $smsapi . "?username=" . $user . "&password=" . $pass . "&tkey=" . $tkey . "&mobile=".$phone."&content=" . urlencode($content)."&productid=" . $prouctID . "&xh=";
//    echo $sendurl;
    $result = file_get_contents($sendurl);
    if (count(explode(',',$result))==2){
        return $statusStr[$result[0]];
    }else{
        return $statusStr[$result];
    }
}

/**
 * @desc 发送验证码
 * @param     $mobile
 * @param     $content
 * @param int $local 0 中国，1国外
 * @return mixed
 */
function sendGjSms($mobile, $content,$local=0)
{
    if ($local==0){
        $account = C('smsname');
        $password = C('smspwd');
        $prouctID = C('smsproductid');
        $smsapi = "http://www.ztsms.cn/sendNSms.do"; //短信网关
        $user = $account; //短信平台帐号
        $tkey = date("YmdHis",time());
        $pass = md5(md5($password).$tkey); //短信平台密码
        $content = $content;//要发送的短信内容
        $phone = $mobile;
        $sendurl = $smsapi . "?username=" . $user . "&password=" . $pass . "&tkey=" . $tkey . "&mobile=".$phone."&content=" . urlencode($content)."&productid=" . $prouctID . "&xh=";
    }else{
        $account = C('smsgjname');
        $password = C('smsgjpwd');
        $prouctID = C('smsgjproductid');
        $smsapi = 'http://www.ztsms.cn/sendGSms.do';
        $user = $account; //短信平台帐号
        $pass = md5($password); //短信平台密码
        $content = $content;//要发送的短信内容
        $phone = $mobile;
        $sendurl = $smsapi . "?username=" . $user . "&password=" . $pass . "&mobile=".$phone."&content=" . urlencode($content)."&productid=" . $prouctID;
    }

    $statusStr = array(
        "0" => "发送短信失败",
        "-1" => "用户名或者密码不正确或用户禁用或者是管理账户",
        "1" =>  "短信发送成功",
        "2" => "余额不够或扣费错误",
        "3" => "扣费失败异常（请联系客服）",
        "6" => "有效号码为空",
        "7" => "短信内容为空",
        "8" => "无签名，必须，格式：【签名】",
        "9" => "没有Url提交权限",
        "10" => "发送号码过多,最多支持2000个号码",
        "11" => "产品ID异常或产品禁用",
        "12" => "参数异常",
        "13" => "tkey参数错误",
        "15" => "Ip验证失败",
        "16" => "xh参数错误",
        "19" => "短信内容过长，最多支持500个,或提交编码异常导致",
    );
   
    $result = file_get_contents($sendurl);
    if (count(explode(',',$result))==2){
        return $statusStr[$result[0]];
    }else{
        return $statusStr[$result];
    }
}

//安全码验证&&版本验证
function validate($data)
{
    $data = $data;
    $safecode = C('safecode');
    $apiversion = C('apiversion');
    if ($safecode == $data['safecode'] && $apiversion == $data['apiversion']) {
        $ReData['code'] = '200';
        $ReData['msg'] = '验证成功!';
        $ReData['data'] = $data;
    } else {
        $ReData['code'] = '-200';
        $ReData['msg'] = '验证失败!';
        $ReData['data'] = $data;
    }
    return $ReData;
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function client_ip($type = 0, $adv = true)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos)
                unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

//token生成
function user_token($data, $uid, $expire_time = 30)
{
    $user_token = md5($uid . $data . date('Y-m-d', time()) . $expire_time);
    $data['uid'] = $uid;
    $data['user_token'] = $user_token;
    $data['expire_time'] = time() + ($expire_time * 60);
    $map['uid'] = $uid;
    $Token = M('token');
    $toekninfo = $Token->where($map)->find();
    if ($toekninfo) {
        $res = $Token->save($data);
        if ($res) {
            return $user_token;
        }
    } else {
        $res = $Token->add($data);
        if ($res) {
            return $user_token;
        }
    }
}

//token校验
function check_token($token)
{
    $map['user_token'] = $token;
    $Token = M('token');
    $tokeninfo = $Token->where($map)->find();
    if ($tokeninfo) {
        return $tokeninfo['uid'];
    } else {
        return false;
    }
}






//获取父级关系ID
function GetPidTree($t_id)
{
    $User = M('User')->find($t_id);
    static $UserList = array();
    $UserList[] = $User['id'];
    if ($User['t_id'] != 0) {
        return GetPidTree($User['t_id']);
    }
    return $UserList;

}
/**
 * @desc  会员返点
 * @param $user_id 用户ID
 */
function vipRebate($user_id){
    $User  = M('User')->find($user_id);
    $Elder = GetPidTree($User['t_id']);
    $GetPidTreecount = count($Elder);
    if($GetPidTreecount >= 3){
        $GetPidTreecount = 3;
    }elseif($GetPidTreecount < 3){
        $GetPidTreecount = $GetPidTreecount;
    }
    for($k=1; $k<=$GetPidTreecount; $k++){
        $FLmap['id'] = $Elder[($k-1)];
        $FLUserinfo = M('User')->where($FLmap)->find();
        switch ($FLUserinfo['level']) {
            case 1:
                if($FLUserinfo['isvip'] == 1){
                    $rebate_amount = C('agent_1_vip_level_'.$k);
                }
                break;
            case 2:
                if($FLUserinfo['isvip'] == 1){
                    $rebate_amount = C('agent_2_vip_level_'.$k);
                }
                break;
            case 3:
                if($FLUserinfo['isvip'] == 1){
                    $rebate_amount = C('agent_3_vip_level_'.$k);
                }
                break;
            default:
                if($FLUserinfo['isvip'] == 1){
                    $rebate_amount = C('agent_1_vip_level_'.$k);
                }
                break;
        }
        $content = '您的下级'.$User['nick_name'].'开通会员';
        addBalance($FLUserinfo['id'],$rebate_amount,10,$content);
    }
}
/*
 * @desc  增加余额
 * @param $user_id 用户ID
 * @param $balance 增加金额
 * @param $cdoe    数据库对照码
 * @param $beizhu  备注
 * */
function addBalance($userid,$balance,$cdoe,$beizhu='无备注'){
    $res = M('user')->where("id = $userid")->setInc('balance',$balance);
    if($res){
        $type   = 1;
        $code   = $cdoe;
        $status = 1;
        money_record($userid,$type,$balance,$code,$status,$beizhu);
        return 1;
    }else{
        $type   = 1;
        $code   = $cdoe;
        $status = 0;
        money_record($userid,$type,$balance,$code,$status,$beizhu);
        return false;
    }

}
/*
 * @desc  减少余额
 * @param $user_id 用户ID
 * @param $balance 减少金额
 * @param $cdoe    数据库对照码
 * @param $beizhu  备注
 * */
function delBalance($userid,$balance,$cdoe,$beizhu='无备注'){
    $res = M('user')->where("id = $userid")->setDec('balance',$balance);
    if($res){
        $type = 2;
        $code = $cdoe;
        $status = 1;
        money_record($userid,$type,$balance,$code,$status,$beizhu);
        return 1;
    }else{
        $type = 2;
        $code = $cdoe;
        $status = 0;
        money_record($userid,$type,$balance,$code,$status,$beizhu);
        return false;
    }
}

/**
 * @desc 获取当前的token值
 * @author Earl <guo@seosite.cn> .
 * @updateTime
 * @param null $type
 * @return mixed|string
 */
function _get_token($type = null)
{
    $token = '';
    if (empty($type)) {
        $token = I('post.token');
        $http_header = getallheaders();
        $static_token = [
            "iss" => $http_header['Origin'], // 签发者
            "aud" => $_SERVER['SERVER_NAME'], // 接收jwt的一方
        ];
        if (empty($token)) {
            $token = \Org\Util\JWT::encode($static_token, C('safecode'));
        }
    } else {
        $token = $_POST[$type];
    }

    $user_info = decode_token($token);

    $map['uid'] = $user_info['id'];
    $map['user_token'] = $token;
    $ret = M('token')->where($map)->find();
    if (empty($ret) || ($ret['expire_time'] < NOW_TIME && $ret['expire_time'] !=0)) $token = '';
    return $token;
}

/**
 * @desc 设置token
 * @author Earl <guo@seosite.cn> .
 * @updateTime
 * @param $data
 * @return string
 */
function _set_token($data,$expire_time = 0)
{
    $token = '';
    if (!empty($data)) {
        $token = \Org\Util\JWT::encode($data, C('safecode'));
    }

    $token_map['uid']       = $data['id'];
    $token_map['platform']  = 'app';

    $token_exist = M('token')->where($token_map)->find();
    $t = NOW_TIME + $expire_time;
    $expire_time = empty($expire_time) ? 0 : $t;
    if ($token_exist) {
        $save_data = [
            'user_token' => $token,
            'expire_time' => $expire_time
        ];
        M('token')->where(array('id' => $token_exist['id']))->save($save_data);
    } else {
        //添加token至token表中
        $add_data = array(
            'uid'           =>  $data['id'],
            'eid'           =>  0,
            'user_token'    =>  $token,
            'platform'      =>  'app',
            'expire_time'   =>  $expire_time
        );
        $ret = M('token')->add($add_data);
    }

    return $token;
}

/**
 * @desc 清空用户token
 * @author Earl <guo@seosite.cn> .
 * @updateTime
 * @param $token
 * @return bool
 */
function _unset_token($token)
{
    $is_exist = M('token')->where(array('user_token' => $token))->find();
    if ($is_exist){
        M('token')->where(array('user_token' => $token))->delete();
    }
    return true;
}
/**
 * @desc 解码token，返回原$data内容
 * @author Earl <guo@seosite.cn> .
 * @updateTime
 * @param $token
 * @return array
 */
function decode_token($token = '')
{
    if (empty($token)) {
        $token = _get_token();
    }
    if (empty($token)){
        return "";
    }
    $info = (array)\Org\Util\JWT::decode($token, C('safecode'), array('HS256'));

//    $info['u_phone'] =$info['phone'] ;
//    $info['phone'] = substr_replace($info['phone'],'****',3,4);
    $info['password'] = '冷链车，智能监控平台!';
//    $info['headsmall'] = !empty($info['headsmall'])?C('site_url').$info['headsmall']:'';
//    list($info['rank'],$info['rank_text']) = userRank($info['id']);

//    $info['rank'] = $info['rank']+1;
//    $info['low'] = $info['rank'];
//    $info['high'] = $info['rank']+2;
//
//    if (empty($info['level'])){
//        $info['jf_percent'] = '0';
//    }else{
//        list($low,$high) = rankScore($info['id']);
//        //占比
//        $fz = $info['level']-$low;
//        $fm = $high - $low;
//        $info['jf_percent'] = round($fz/$fm,2);
//    }
    return $info;
}
function userRank($uid)
{
    $balance = M('user')->where(array('id'=>$uid))->getField('level');
    if ($balance<10){
        $rank = 0;
        $rank_text = '一级会员';
    }else if($balance<30){
        $rank = 1;
        $rank_text = '一级会员';
    }else if($balance<70){
        $rank = 2;
        $rank_text = '二级会员';
    }else if($balance<190){
        $rank = 3;
        $rank_text = '三级会员';
    }else if($balance<385){
        $rank = 4;
        $rank_text = '四级会员';
    }else if($balance<640){
        $rank = 5;
        $rank_text = '五级会员';
    }else if($balance<1040){
        $rank = 6;
        $rank_text = '六级会员';
    }else if($balance<1665){
        $rank = 7;
        $rank_text = '七级会员';
    }else if($balance<2715){
        $rank = 8;
        $rank_text = '八级会员';
    }else if($balance<4290){
        $rank = 9;
        $rank_text = '九级会员';
    }else if($balance<6690){
        $rank = 10;
        $rank_text = '十级会员';
    }else if($balance<9840){
        $rank = 11;
        $rank_text = '十一级会员';
    }else if($balance<14840){
        $rank = 12;
        $rank_text = '十二级会员';
    }else if($balance<20840){
        $rank = 13;
        $rank_text = '十三级会员';
    }else if($balance<27340){
        $rank = 14;
        $rank_text = '十四级会员';
    }else if($balance<34500){
        $rank = 15;
        $rank_text = '十五级会员';
    }else if($balance<42700){
        $rank = 16;
        $rank_text = '十六级会员';
    }else if($balance<52580){
        $rank = 17;
        $rank_text = '十七级会员';
    }else if($balance<65400){
        $rank = 18;
        $rank_text = '十八级会员';
    }else if($balance<83400){
        $rank = 19;
        $rank_text = '十九级会员';
    }else if($balance<110000){
        $rank = 20;
        $rank_text = '二十级会员';
    }else if($balance<140000){
        $rank = 21;
        $rank_text = '二十一级会员';
    }else if($balance<175000){
        $rank = 22;
        $rank_text = '二十二级会员';
    }else if($balance<215000){
        $rank = 23;
        $rank_text = '二十三级会员';
    }else if($balance<268000){
        $rank = 24;
        $rank_text = '二十四级会员';
    }else if($balance<345000){
        $rank = 25;
        $rank_text = '二十五级会员';
    }else if($balance<454000){
        $rank = 26;
        $rank_text = '二十六级会员';
    }else if($balance<588000){
        $rank = 27;
        $rank_text = '二十七级会员';
    }else if($balance<760000){
        $rank = 28;
        $rank_text = '二十八级会员';
    }else if($balance<1000000){
        $rank = 29;
        $rank_text = '二十九级会员';
    }else if($balance>1000000){
        $rank = 30;
        $rank_text = '三十级会员';
    }

    return array($rank,$rank_text);
}

function userRank2($uid)
{
    $level = M('user')->where(array('id'=>$uid))->getField('level');
    if ($level<10){
        $rank = 1;
        $rank_text = '一级会员';
    }else if($level<30){
        $rank = 2;
        $rank_text = '一级会员';
    }else if($level<70){
        $rank = 3;
        $rank_text = '二级会员';
    }else if($level<190){
        $rank = 4;
        $rank_text = '三级会员';
    }else if($level<385){
        $rank = 5;
        $rank_text = '四级会员';
    }else if($level<640){
        $rank = 6;
        $rank_text = '五级会员';
    }else if($level<1040){
        $rank = 7;
        $rank_text = '六级会员';
    }else if($level<1665){
        $rank = 8;
        $rank_text = '七级会员';
    }else if($level<2715){
        $rank = 9;
        $rank_text = '八级会员';
    }else if($level<4290){
        $rank = 10;
        $rank_text = '九级会员';
    }else if($level<6690){
        $rank = 11;
        $rank_text = '十级会员';
    }else if($level<9840){
        $rank = 12;
        $rank_text = '十一级会员';
    }else if($level<14840){
        $rank = 13;
        $rank_text = '十二级会员';
    }else if($level<20840){
        $rank = 14;
        $rank_text = '十三级会员';
    }else if($level<27340){
        $rank = 15;
        $rank_text = '十四级会员';
    }else if($level<34500){
        $rank = 16;
        $rank_text = '十五级会员';
    }else if($level<42700){
        $rank = 17;
        $rank_text = '十六级会员';
    }else if($level<52580){
        $rank = 18;
        $rank_text = '十七级会员';
    }else if($level<65400){
        $rank = 19;
        $rank_text = '十八级会员';
    }else if($level<83400){
        $rank = 20;
        $rank_text = '十九级会员';
    }else if($level<110000){
        $rank = 21;
        $rank_text = '二十级会员';
    }else if($level<140000){
        $rank = 22;
        $rank_text = '二十一级会员';
    }else if($level<175000){
        $rank = 23;
        $rank_text = '二十二级会员';
    }else if($level<215000){
        $rank = 24;
        $rank_text = '二十三级会员';
    }else if($level<268000){
        $rank = 25;
        $rank_text = '二十四级会员';
    }else if($level<345000){
        $rank = 26;
        $rank_text = '二十五级会员';
    }else if($level<454000){
        $rank = 27;
        $rank_text = '二十六级会员';
    }else if($level<588000){
        $rank = 28;
        $rank_text = '二十七级会员';
    }else if($level<760000){
        $rank = 29;
        $rank_text = '二十八级会员';
    }else if($level<1000000){
        $rank = 30;
        $rank_text = '二十九级会员';
    }else if($level>1000000){
        $rank = 31;
        $rank_text = '三十级会员';
    }

    return array($rank,$rank_text);
}


function rankScore($uid)
{
    $balance = M('user')->where(array('id'=>$uid))->getField('level');
    if ($balance<10){
        $low = 0;
        $high = 10;
    }else if($balance<30){
        $low = 10;
        $high = 30;
    }else if($balance<70){
        $low = 30;
        $high = 70;
    }else if($balance<190){
        $low = 70;
        $high = 190;
    }else if($balance<385){
        $low = 190;
        $high = 385;
    }else if($balance<640){
        $low = 385;
        $high = 640;
    }else if($balance<1040){
        $low = 640;
        $high = 1040;
    }else if($balance<1665){
        $low = 1040;
        $high = 1665;
    }else if($balance<2715){
        $low = 1665;
        $high = 2715;
    }else if($balance<4290){
        $low = 2715;
        $high = 4290;
    }else if($balance<6690){
        $low = 4290;
        $high = 6690;
    }else if($balance<9840){
        $low = 6690;
        $high = 9840;
    }else if($balance<14840){
        $low = 9840;
        $high = 14840;
    }else if($balance<20840){
        $low = 14840;
        $high = 20840;
    }else if($balance<27340){
        $low = 20840;
        $high = 27340;
    }else if($balance<34500){
        $low = 27340;
        $high = 34500;
    }else if($balance<42700){
        $low = 34500;
        $high = 42700;
    }else if($balance<52580){
        $low = 42700;
        $high = 52580;
    }else if($balance<65400){
        $low = 52580;
        $high = 65400;
    }else if($balance<83400){
        $low = 65400;
        $high = 83400;
    }else if($balance<110000){
        $low = 83400;
        $high = 110000;
    }else if($balance<140000){
        $low = 110000;
        $high = 140000;
    }else if($balance<175000){
        $low = 140000;
        $high = 175000;
    }else if($balance<215000){
        $low = 175000;
        $high = 215000;
    }else if($balance<268000){
        $low = 215000;
        $high = 268000;
    }else if($balance<345000){
        $low = 268000;
        $high = 345000;
    }else if($balance<454000){
        $low = 345000;
        $high = 454000;
    }else if($balance<588000){
        $low = 454000;
        $high = 588000;
    }else if($balance<760000){
        $low = 588000;
        $high = 760000;
    }else if($balance<1000000){
        $low = 760000;
        $high = 1000000;
    }else if($balance>1000000){
        $low = 1000000;
        $high = '';
    }

    return array($low,$high);
}

/**
 * @desc 返回用户昵称和头像
 * @author Earl <guo@seosite.cn> .
 * @updateTime
 * @param $uid
 * @return array|string
 */
function getUserNameAndHeadByID($uid)
{
    switch ($uid){
        case -1:
            break;
        case -2:
            break;
        case -3:
            break;
        case -4:
            break;
    }
    $info = M('user')->find($uid);
    if (empty($info)) return "";
    return array($info['nickname'], $info['headsmall']);
}

/**
 * PHP DES 加密程式
 *
 * @param $key 密鑰（必须要八个字符）
 * @param $encrypt 要加密的明文
 * @return string 密文
 */
function do_encrypt ($encrypt)
{
    // 根據 PKCS#7 RFC 5652 Cryptographic Message Syntax (CMS) 修正 Message 加入 Padding
    $block = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_ECB);
    $pad = $block - (strlen($encrypt) % $block);
    $encrypt .= str_repeat(chr($pad), $pad);

    // 不需要設定 IV 進行加密
    $passcrypt = mcrypt_encrypt(MCRYPT_DES, C('DES_KEY'), $encrypt, MCRYPT_MODE_ECB);
    return base64_encode($passcrypt);
}

/**
 * PHP DES 解密程式
 *
 * @param $key 密鑰（必须要八个字符）
 * @param $decrypt 要解密的密文
 * @return string 明文
 */
function do_decrypt ( $decrypt)
{
    // 不需要設定 IV
    $str = mcrypt_decrypt(MCRYPT_DES, C('DES_KEY'), base64_decode($decrypt), MCRYPT_MODE_ECB);

    // 根據 PKCS#7 RFC 5652 Cryptographic Message Syntax (CMS) 修正 Message 移除 Padding
    $pad = ord($str[strlen($str) - 1]);
    return substr($str, 0, strlen($str) - $pad);
}

/**
 * @desc 返回两个球面之间的距离
 * @param $lat1
 * @param $lng1
 * @param $lat2
 * @param $lng2
 * @return int
 */
function haversine_distance($lat1, $lng1, $lat2, $lng2) {
    $EARTH_RADIUS = 6371.00;   // 地球平均半径，6371km
    // 角度转换成弧度
    $rlat1 = deg2rad($lat1);
    $rlng1 = deg2rad($lng1);
    $rlat2 = deg2rad($lat2);
    $rlng2 = deg2rad($lng2);

    $rlat_diff = abs($rlat1 - $rlat2);
    $rlng_diff = abs($rlng1 - $rlng2);

    $h = pow(sin($rlat_diff / 2), 2) + cos($rlat1) * cos($rlat2) * pow(sin($rlng_diff / 2), 2);
    return 2 * $EARTH_RADIUS * asin(sqrt($h));
}

function get_first_char( $str )
{
    $fchar = $str[0];
    if ( ord( "A" ) <= ord( $fchar ) && ord( $fchar ) <= ord( "z" ) )
    {
        return strtoupper( $fchar );
    }
    $str = iconv( "UTF-8", "gb2312", $str );
    $asc = ord( $str[0] ) * 256 + ord( $str[1] ) - 65536;
    if ( -20319 <= $asc && $asc <= -20284 )
    {
        return "A";
    }
    if ( -20283 <= $asc && $asc <= -19776 )
    {
        return "B";
    }
    if ( -19775 <= $asc && $asc <= -19219 )
    {
        return "C";
    }
    if ( -19218 <= $asc && $asc <= -18711 )
    {
        return "D";
    }
    if ( -18710 <= $asc && $asc <= -18527 )
    {
        return "E";
    }
    if ( -18526 <= $asc && $asc <= -18240 )
    {
        return "F";
    }
    if ( -18239 <= $asc && $asc <= -17923 )
    {
        return "G";
    }
    if ( -17922 <= $asc && $asc <= -17418 )
    {
        return "H";
    }
    if ( -17417 <= $asc && $asc <= -16475 )
    {
        return "I";
    }
    if ( -16474 <= $asc && $asc <= -16213 )
    {
        return "J";
    }
    if ( -16212 <= $asc && $asc <= -15641 )
    {
        return "K";
    }
    if ( -15640 <= $asc && $asc <= -15166 )
    {
        return "L";
    }
    if ( -15165 <= $asc && $asc <= -14923 )
    {
        return "M";
    }
    if ( -14922 <= $asc && $asc <= -14915 )
    {
        return "N";
    }
    if ( -14914 <= $asc && $asc <= -14631 )
    {
        return "P";
    }
    if ( -14630 <= $asc && $asc <= -14150 )
    {
        return "Q";
    }
    if ( -14149 <= $asc && $asc <= -14091 )
    {
        return "R";
    }
    if ( -14090 <= $asc && $asc <= -13319 )
    {
        return "S";
    }
    if ( -13318 <= $asc && $asc <= -12839 )
    {
        return "T";
    }
    if ( -12838 <= $asc && $asc <= -12557 )
    {
        return "W";
    }
    if ( -12556 <= $asc && $asc <= -11848 )
    {
        return "X";
    }
    if ( -11847 <= $asc && $asc <= -11056 )
    {
        return "Y";
    }
    if ( -11055 <= $asc && $asc <= -10247 )
    {
        return "Z";
    }
}

?>